<template>
  <view class="app-layout">
    <app-header :title="tit" />
    <view class="app-main">
      <view class="form-container">
        <view class="class-form">
          <scroll-view scroll-y="true" style="height: 100%;">
            <u-form labelPosition="left" labelWidth="90px" :model="formData" ref="refFrom">
              <view class="page-product-form-info">
                <u-form-item label="上级分类">
                  <uni-data-select v-model="formData.parentId" placeholder="请选择一级分类，不选择默认为一级大类" :localdata="range"
                    @change="change"></uni-data-select>
                </u-form-item>
                <u-form-item label="分类名称" required>
                  <uni-easyinput placeholder="请输入" clearable v-model="formData.categoryName" :maxlength="10">
                    <template #right>
                      <text class="suffix-num">{{ (formData.categoryName || '').length }}/10</text>
                    </template>
                  </uni-easyinput>
                </u-form-item>

                <view class="special-formitem">
                  <u-form-item label="分类图标" required class="img2">
                    <uploadImage :initial-images="uploadedImagesOne" @upload-success="handleUpload"
                      @remove="handleRemove" />
                    <view style="color: #999999; font-size: 14px; margin-bottom: 4px">建议尺寸：200*200px，大小不超过3MB</view>
                  </u-form-item>
                </view>
                <u-form-item label="分类排序" required>
                  <uni-easyinput placeholder="请输入" clearable v-model="formData.sortOrder" type="number"></uni-easyinput>
                </u-form-item>
                <u-form-item label="分类状态" required>
                  <u-switch v-model="formData.isActive" size="20" :activeValue="1" :inactiveValue="0"
                    activeColor="#20D048"></u-switch>
                </u-form-item>
                <u-form-item label="分类描述">
                  <u-textarea v-model="formData.description" :placeholder="'请输入'" :maxlength="2000" :rows="5"
                    :autosize="true" count></u-textarea>

                </u-form-item>
              </view>
            </u-form>
          </scroll-view>
        </view>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref,
    computed
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getTreeCategory,
    updateSassCategoryById,
    addSassCategory
  } from '@/requests/apis/products'
  import
  uploadImage
  from '@/components/upload-image/index.vue'
  let tit = ref('新增商品分类')
  let formData = ref({
    isActive: 1,
  })
  let fileList2 = ref([])
  let range = ref([])
  const uploadedImagesOne = ref([]);
  onLoad((e) => {
    getCategoryList()
    if (e.infoList) {
      tit.value = '编辑商品分类'
      let data = JSON.parse(decodeURIComponent(e.infoList))
      console.log(data, '11111')
      formData.value.categoryName = data.categoryName
      formData.value.categoryId = data.categoryId
      formData.value.sortOrder = data.sortOrder
      formData.value.isActive = data.isActive
      formData.value.description = data.description || ''
      formData.value.parentId = data.parentId
      if (data?.categoryIcon) {
        uploadedImagesOne.value[0] = data.categoryIcon
      }
    }
  })
  // 获取上级分类数据
  const getCategoryList = async () => {
    let res = await getTreeCategory({})
    let arr = res.Result || []
    let arr2 = arr.map((item) => ({
      text: item.categoryName,
      value: item.categoryId,
    }))
    // 后续使用 arr2（如给选择器赋值）
    range.value = arr2
  }


  // 处理上传成功事件
  const handleUpload = (imageUrl) => {
    uploadedImagesOne.value[0] = imageUrl
  };

  // 处理删除事件
  const handleRemove = (removedUrl) => {
    uploadedImagesOne.value = []
  };
  const submit = () => {
    console.log(formData.value.isActive)
    const valid = [{
        k: 'categoryName',
        err: '请输入分类名称',
      },
      {
        k: 'sortOrder',
        err: '请输入分类排序',
      },

    ]

    let err = ''
    if (!uploadedImagesOne.value?.length) {
      err = '请上传分类图标'
    }
    for (let item of valid) {
      if (!formData.value[item.k] && formData.value[item.k] !== 0) {
        err = item.err
        break
      }
    }
    if (err) {
      uni.showToast({
        title: err,
        icon: 'none',
        duration: 2000,
      })
    } else {
      submitReq()
    }

  }
  const submitReq = async () => {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })

    let postData = JSON.parse(JSON.stringify(formData.value))
    postData.sortOrder = Number(postData.sortOrder)
    postData.categoryIcon = uploadedImagesOne.value
      .map((item) => {
        return item
      })
      .join(',')

    const fn = formData.value.categoryId ? updateSassCategoryById : addSassCategory
    try {
      const res = await fn(postData)
      console.log(res, 'resres')

      if (res) {
        uni.showToast({
          title: res.Result || "",
          icon: 'success',
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 800)
      }
      uni.hideLoading()
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }
</script>
<style lang="scss" scoped>
  .form-container {
    width: 100%;
    background: #fff;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;
    .class-form {
      flex: 1;
      overflow: hidden;

      :deep(.u-form) {
        padding: 48px 280px 0;
        box-sizing: border-box;
      }

      .suffix-num {
        font-weight: 400;
        font-size: 14px;
        color: rgba(51, 70, 129, 0.6);
        padding-right: 10px;
        box-sizing: border-box;
      }
    }
  }
</style>
